import { useState, useEffect, useRef, useContext } from 'react'
import { Table, Form, Button, Input, Modal, message } from 'antd'
import { path, configContext, getLocalValue } from '../../config/env'

function Node() {
  const [tableData, setData] = useState([])
  const [loading, setLoading] = useState(true)
  const [param, setParam] = useState({
    id: '',
    ip: '',
    type: ''
  })
  const [nodeId, setNodeId] = useState('')
  const [height, setHeight] = useState(600)
  const tableRef = useRef<any>()
  const [showModal, updateModal] = useState(false)

  const localValue = useContext(configContext)

  useEffect(() => {
    getData()
    if (tableRef.current && tableRef.current.offsetHeight) {
      setHeight(tableRef.current.offsetHeight)
    }
  }, [])

  const getData = () => {
    setData([])
    setLoading(true)
    fetch(path + '/live_trans_node_info')
    .then((response) => response.json())
    .then((data) => {
      setLoading(false)
      if (data) {
        const value = data.filter((item:any) => {
          return (param.id ? param.id == item.node_id : true) && (param.ip ? param.ip == item.node_ip : true) && (param.type ? param.type == item.node_type : true)
        })
        setData(value || [])
      }
    })
  }
  
  const getParamValue = (e:any, type:string) => {
    setParam({
      ...param,
      [type]: e.target.value
    })
  }


  return ( 
     <div className='table-content' ref={tableRef}>
       <div className='title'>{getLocalValue(localValue, '直播节点','live node')}</div>
       <div className='table'>
        <div className='form'>
        <Form layout='inline'>
          <Form.Item label={getLocalValue(localValue, '节点ID','node ID')}>
            <Input style={{width: 200}} value={param.id} allowClear onChange={(e) => getParamValue(e, 'id')} />
          </Form.Item>
          <Form.Item label={getLocalValue(localValue, '节点IP','node IP')}>
            <Input style={{width: 200}} value={param.ip} allowClear onChange={(e) => getParamValue(e, 'ip')} />
          </Form.Item>
          <Form.Item label={getLocalValue(localValue, '节点类型','node type')}>
            <Input style={{width: 200}} value={param.type} allowClear onChange={(e) => getParamValue(e, 'type')} />
          </Form.Item>
          <Form.Item>
            <Button type="primary" onClick={getData}>{getLocalValue(localValue, '查询','query')}</Button>
          </Form.Item>
        </Form>
        </div>
        <Table loading={loading} dataSource={tableData} pagination={false} scroll={{y: height - 200}} rowKey='node_id' columns={
          [{
            title: getLocalValue(localValue, '节点ID','node ID'),
            dataIndex: 'node_id',
            width: 100
          },
          {
            title: getLocalValue(localValue, '节点IP','node IP'),
            dataIndex: 'node_ip',
            width: 130
          },
          {
            title: getLocalValue(localValue, '节点类型','node type'),
            dataIndex: 'node_type',
            width: 160,
            render: (value) => {
              return value == 'NODE_TYPE_LIVE_CAPTRANS' ?  getLocalValue(localValue, '采集传输节点', 'acquisition and transmission node') : value  == 'NODE_TYPE_LIVE_CACHETRANS' ? getLocalValue(localValue, '缓存传输结点', 'cache transfer node') : value == 'NODE_TYPE_LIVE_EDGETRANS' ? getLocalValue(localValue, '边缘传输结点', 'edge transmission node') : value
            },
          },
          {
            title: 'exchange_name',
            dataIndex: 'exchange_name'
          },
          {
            title: 'queue_name',
            dataIndex: 'queue_name'
          },
          {
            title: 'router_key',
            dataIndex: 'router_key'
          },
          {
            title: 'area_id',
            dataIndex: 'area_id',
            width: 100
          },
          {
            title: getLocalValue(localValue, '描述','description'),
            dataIndex: 'description'
          },
          {
            title: getLocalValue(localValue, '操作','action field'),
            width: 130,
            render: (row) => {
              return (row.node_type == 'NODE_TYPE_LIVE_CAPTRANS' || row.node_type == 'NODE_TYPE_LIVE_CACHETRANS') && <Button type="link" size='small' onClick={() => { setNodeId(row.node_id);updateModal(true) }}>{getLocalValue(localValue, '注入频道','injection channel')}</Button>
            }
          }]
        } ></Table>
       </div>

       <ChannelModal localValue={localValue} nodeId={nodeId} showModal={showModal} updateModal={() => { updateModal(false) }}></ChannelModal>

     </div>
  )
}

function ChannelModal (prop: {nodeId: string, showModal: boolean, updateModal: Function, localValue: string}) {
  const { localValue } = prop
  const [form, setForm] = useState({
    channel_id: '',
    channel_name: '',
    streamsource_addr: '',
    capture_node_id: '',
    cache_node_id: '',
    bitrate: ''
  })

  const updateFormValue = (e:any, type: string) => {
     setForm({
       ...form,
       [type]: e.target.value
     })
  }

  const updateData = () => {
    prop.updateModal()
    fetch(path + '/livecms_live_import',{
      method: 'POST',
      body: JSON.stringify({...form, node_id: prop.nodeId})
    })
    .then((response) => response.json())
    .then((data) => {
      if (data) {
        message.success(getLocalValue(localValue, '注入直播频道成功', 'the live channel was successfully injected'))
      }
    })
  }

  return <Modal title={getLocalValue(localValue, '注入频道', 'injection channel')} width={600} open={prop.showModal} maskClosable={false}	 okText={getLocalValue(localValue, '确定', 'OK')} cancelText={getLocalValue(localValue, '取消', 'cancel')} onOk={updateData} onCancel={() => { prop.updateModal() }} >
    <Form layout='inline' labelCol={{span: 6}}>
      <Form.Item label={getLocalValue(localValue, '节点ID', 'node ID')} style={{marginTop: '20px', width: '100%'}}>
        <p>{prop.nodeId}</p>
      </Form.Item>
      <Form.Item label={getLocalValue(localValue, '频道ID', 'channel ID')} style={{marginTop: '20px', width: '100%'}}>
        <Input style={{width: '100%'}} value={form.channel_id} allowClear onChange={(e) => updateFormValue(e, 'channel_id')} />
      </Form.Item>
      <Form.Item label={getLocalValue(localValue, '频道名称', 'channel name')} style={{marginTop: '20px', width: '100%'}}>
        <Input style={{width: '100%'}} value={form.channel_name} allowClear onChange={(e) => updateFormValue(e, 'channel_name')} />
      </Form.Item>
      <Form.Item label="streamsource_addr" style={{marginTop: '20px', width: '100%'}}>
        <Input style={{width: '100%'}} value={form.streamsource_addr} allowClear onChange={(e) => updateFormValue(e, 'streamsource_addr')} />
      </Form.Item>
      <Form.Item label="capture_node_id" style={{marginTop: '20px', width: '100%'}}>
        <Input style={{width: '100%'}} value={form.capture_node_id} allowClear onChange={(e) => updateFormValue(e, 'capture_node_id')} />
      </Form.Item>
      <Form.Item label="cache_node_id" style={{marginTop: '20px', width: '100%'}}>
        <Input style={{width: '100%'}} value={form.cache_node_id} allowClear onChange={(e) => updateFormValue(e, 'cache_node_id')} />
      </Form.Item>
      <Form.Item label="bitrate" style={{marginTop: '20px', width: '100%'}}>
        <Input style={{width: '100%'}} value={form.bitrate} allowClear onChange={(e) => updateFormValue(e, 'bitrate')} />
      </Form.Item>
    </Form>
  </Modal>
}

export default Node